﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VoiceAd.Models;
using VoiceAd.DAL;
using System.Web.Security;
using System.IO;
using System.Net.Mail;
using System.Net;

namespace VoiceAd.Controllers
{
    public class admincpController : Controller
    {
        private IAudioCampRepository audioCampRepository = new AudioCampRepository(new dbVoiceAdDataContext());
        private IProvinceRepository provinceRepository = new ProvinceRepository(new dbVoiceAdDataContext());
        private IDistrictRepository districtRepository = new DistrictRepository(new dbVoiceAdDataContext());
        private ISectionRepository sectionRepository = new SectionRepository(new dbVoiceAdDataContext());
        private ICustomerRepository customerRepository = new CustomerRepository(new dbVoiceAdDataContext());
        private ICompanyRepository companyRepository = new CompanyRepository(new dbVoiceAdDataContext());
        private IStationRepository stationRepository = new StationRepository(new dbVoiceAdDataContext());
        private IServicesRepository servicesRepository = new ServicesRepository(new dbVoiceAdDataContext());
        private IBroadCastRepository broadCastRepository = new BroadCastRepository(new dbVoiceAdDataContext());
        private ICampaignRepository campaignRepository = new CampaignRepository(new dbVoiceAdDataContext());
        private IBookingRepository bookingRepostitory = new BookingRepository(new dbVoiceAdDataContext());
        private IBlockRepository blockingRepository = new BlockRepository(new dbVoiceAdDataContext());
        private IMonitorRepository monitorRepository = new MonitorRepository(new dbVoiceAdDataContext());
        private ISendMailStatusRepository sendMailStatusRepository = new SendMailStatusRepository(new dbVoiceAdDataContext());
        private IEmailContentRepository emailContentRepository = new EmailContentRepository(new dbVoiceAdDataContext());
        private IlogRepository logRepository = new LogRepository(new dbVoiceAdDataContext());
        private ISendMailGroupRepository sendMailGroupRepository = new SendMailGroupRepository(new dbVoiceAdDataContext());
        private IContentRepository contentRepository = new ContentRepository(new dbVoiceAdDataContext());

        private const string hsTextNhanVien = "Chọn nhân viên";

        [Authorize(Roles = "admin, account, media, manager, supervisor, director")]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "admin, media, manager")]
        public ActionResult SendMailStatus()
        {
            ViewBag.stt = 1;
            return View(sendMailStatusRepository.GetListSendMailStatus());
        }

        [Authorize(Roles = "admin")]
        public ActionResult Log(string name, string UserName)
        {
            string s = string.Format("{0}", RouteData.Values["name"]);
            string strPage = string.IsNullOrEmpty(s) || !VoiceAd.Common.MyFunction.ValidateNumber(s) ? "1" : s;

            int intPageSize = 15;
            var lst = logRepository.GetByUserNameLog(UserName);
            int intSum = lst.Count();
            int intDu = intSum % intPageSize;
            int intPage = intSum / intPageSize;
            if (intDu > 0)
                intPage++;

            int intPos = (int.Parse(strPage) * intPageSize - intPageSize);
            ViewBag.stt = intPos + 1;
            string strAction = Url.Content("~/log-");

            ViewBag.paging = strPage;
            ViewBag.SumPage = intPage;
            ViewBag.lstPage = VoiceAd.Common.MyFunction.lstPaging(intPage, int.Parse(strPage), strAction);
            ViewBag.Action = strAction;
            return View(logRepository.GetByUserNameLog(UserName).Skip(intPos).Take(intPageSize));
        }

        [Authorize(Roles = "admin, media, manager")]
        public ActionResult DeleteSendMailStatus(int id)
        {
            try
            {
                tblLog tbl = new tblLog();
                tbl.UserName = Membership.GetUser().UserName;
                tbl.CreateDate = DateTime.Now;
                tbl.ActionName = "Delete SendMail Status";
                tblSendMailStatus tblsendmail = sendMailStatusRepository.GetSendMailStatusById(id);
                tbl.Description = "Chiến dịch: " + campaignRepository.GetCampaignById(Convert.ToInt32(tblsendmail.CampaingId)).Title + " - Email: " + tblsendmail.Email;
                logRepository.InsLog(tbl);

                sendMailStatusRepository.DelSendMailStatus(id);

                return RedirectToAction("SendMailStatus");
            }
            catch
            {
                return RedirectToAction("SendMailStatus");
            }
        }

        [Authorize(Roles = "admin, media, manager")]
        public ActionResult EmailContent()
        {
            return View(emailContentRepository.GetList());
        }

        [Authorize(Roles = "admin, media, manager")]
        public ActionResult CreateEmailContent()
        {
            return View();
        }

        [Authorize(Roles = "admin, media, manager")]
        [HttpPost, ValidateInput(false)]
        public ActionResult CreateEmailContent(tblEmailContent tbl)
        {
            try
            {
                emailContentRepository.InsEmailContent(tbl);

                tblLog tbllog = new tblLog();
                tbllog.UserName = Membership.GetUser().UserName;
                tbllog.CreateDate = DateTime.Now;
                tbllog.ActionName = "Create Email Content";
                tbllog.Description = tbl.Title;
                logRepository.InsLog(tbllog);

                return RedirectToAction("EmailContent");
            }
            catch
            {
                return View();
            }
        }

        [Authorize(Roles = "admin, media, manager")]
        public ActionResult EditEmailContent(int id)
        {
            return View(emailContentRepository.GetById(id));
        }

        [Authorize(Roles = "admin, media, manager")]
        [HttpPost, ValidateInput(false)]
        public ActionResult EditEmailContent(tblEmailContent tbl)
        {
            try
            {
                emailContentRepository.UpdEmailContent(tbl);

                tblLog tbllog = new tblLog();
                tbllog.UserName = Membership.GetUser().UserName;
                tbllog.CreateDate = DateTime.Now;
                tbllog.ActionName = "Edit Email Content";
                tbllog.Description = tbl.Title;
                logRepository.InsLog(tbllog);

                return RedirectToAction("EmailContent");
            }
            catch
            {
                return View();
            }
        }

        [Authorize(Roles = "admin, media, manager")]
        public ActionResult DeleteEmailContent(int id)
        {
            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = "Delete Email Content";
            tblEmailContent tbl = emailContentRepository.GetById(id);
            tbllog.Description = tbl.Title;
            logRepository.InsLog(tbllog);

            emailContentRepository.DelEmailContent(id);
            return RedirectToAction("EmailContent");
        }

        public void GetProvince(object obj = null)
        {
            var lst = provinceRepository.GetListProvinces().ToList();
            tblProvince tbl = new tblProvince { Id = -1, ProvinceName = "Chọn tỉnh thành" };
            lst.Insert(0, tbl);
            ViewBag.lstProvince = new SelectList(lst, "Id", "ProvinceName", obj);
        }

        public void GetStation(object obj = null)
        {
            var lst = stationRepository.GetListStations().ToList();
            tblStation tbl = new tblStation { Id = -1, StationName = "Chọn nhà đài" };
            lst.Insert(0, tbl);
            ViewBag.lstStation = new SelectList(lst, "Id", "StationName", obj);
        }

        //GetSection
        public void GetSection(object obj = null)
        {
            var lst = sectionRepository.GetListSections().ToList();
            tblSection tbl = new tblSection { Id = -1, SectionName_Vn = "Chọn khung giờ" };
            lst.Insert(0, tbl);
            ViewBag.lstSection = new SelectList(lst, "Id", "SectionName_Vn", obj);
        }

        public void GetDistrict(object obj = null)
        {
            var lst = districtRepository.GetListDistricts().ToList();
            tblDistrict tbl = new tblDistrict { Id = -1, DistrictName = "Chọn quận huyện" };
            lst.Insert(0, tbl);
            ViewBag.lstDistrict = new SelectList(lst, "Id", "DistrictName", obj);
        }

        public void GetDistrictByProvince(int ProvinceID, object obj = null)
        {
            var lst = from p in districtRepository.GetListDistricts() where p.ProvinceId == ProvinceID select p;
            ViewBag.lstDistrict = new SelectList(lst, "Id", "DistrictName", obj);
        }

        [Authorize(Roles = "admin")]
        public ActionResult Province(string name, string ProvinceName)
        {
            string s = string.Format("{0}", RouteData.Values["name"]);
            string strPage = string.IsNullOrEmpty(s) || !VoiceAd.Common.MyFunction.ValidateNumber(s) ? "1" : s;

            int intPageSize = 15;
            var lst = provinceRepository.GetListSearchProvinces(ProvinceName);
            int intSum = lst.Count();
            int intDu = intSum % intPageSize;
            int intPage = intSum / intPageSize;
            if (intDu > 0)
                intPage++;

            int intPos = (int.Parse(strPage) * intPageSize - intPageSize);
            ViewBag.stt = intPos + 1;

            string strAction = Url.Content("~/province-");

            ViewBag.paging = strPage;
            ViewBag.SumPage = intPage;
            ViewBag.lstPage = VoiceAd.Common.MyFunction.lstPaging(intPage, int.Parse(strPage), strAction);
            ViewBag.Action = strAction;
            ViewBag.LstProvinces = provinceRepository.GetListSearchProvinces(ProvinceName).Skip(intPos).Take(intPageSize);
            return View();
        }

        [Authorize(Roles = "admin")]
        public ActionResult CreateProvince()
        {
            return View();
        }

        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult CreateProvince(tblProvince tbl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    provinceRepository.InsProvince(tbl);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Create Province";
                    tbllog.Description = tbl.ProvinceName;
                    logRepository.InsLog(tbllog);
                }
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình thêm mới");
            }
            return RedirectToAction("Province", new { name = 1 });
        }

        //
        // GET: /Province/Edit/5
        [Authorize(Roles = "admin")]
        public ActionResult EditProvince(int id)
        {
            return View(provinceRepository.GetProvinceById(id));
        }

        //
        // POST: /Province/Edit/5
        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult EditProvince(tblProvince tbl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    provinceRepository.UpdProvince(tbl);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Edit Province";
                    tbllog.Description = tbl.ProvinceName;
                    logRepository.InsLog(tbllog);
                }
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình lưu");
            }
            return RedirectToAction("Province", new { name = 1 });
        }

        //
        // POST: /Province/Delete/5
        [Authorize(Roles = "admin")]
        public ActionResult DeleteProvince(int id)
        {
            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = "Delete Province";
            tblProvince tbl = provinceRepository.GetProvinceById(id);
            tbllog.Description = tbl.ProvinceName;
            logRepository.InsLog(tbllog);

            provinceRepository.DelProvince(id);
            return RedirectToAction("Province", new { name = 1 });
        }

        ////
        ///End
        ///
        ////
        ///Manage District
        ///
        //
        // GET: /District/
        [Authorize(Roles = "admin")]
        public ActionResult District(string name, string DistrictName)
        {
            string s = string.Format("{0}", RouteData.Values["name"]);
            string strPage = string.IsNullOrEmpty(s) || !VoiceAd.Common.MyFunction.ValidateNumber(s) ? "1" : s;

            int intPageSize = 15;
            var lst = districtRepository.GetListSearchDistricts(DistrictName);
            int intSum = lst.Count();
            int intDu = intSum % intPageSize;
            int intPage = intSum / intPageSize;
            if (intDu > 0)
                intPage++;

            int intPos = (int.Parse(strPage) * intPageSize - intPageSize);
            ViewBag.stt = intPos + 1;
            string strAction = Url.Content("~/district-");

            ViewBag.paging = strPage;
            ViewBag.SumPage = intPage;
            ViewBag.lstPage = VoiceAd.Common.MyFunction.lstPaging(intPage, int.Parse(strPage), strAction);
            ViewBag.Action = strAction;
            return View(districtRepository.GetListSearchDistricts(DistrictName).Skip(intPos).Take(intPageSize));
        }

        //
        // GET: /District/Create
        [Authorize(Roles = "admin")]
        public ActionResult CreateDistrict()
        {
            GetProvince();
            return View();
        }

        //
        // POST: /District/Create
        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult CreateDistrict(tblDistrict tbl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    districtRepository.InsDistrict(tbl);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Create District";
                    tbllog.Description = tbl.DistrictName;
                    logRepository.InsLog(tbllog);

                    return RedirectToAction("District", new { name = 1 });
                }
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình thêm mới");
            }
            return RedirectToAction("District", new { name = 1 });
        }

        //
        // GET: /District/Edit/5
        [Authorize(Roles = "admin")]
        public ActionResult EditDistrict(int id)
        {
            tblDistrict tbl = districtRepository.GetDistrictById(id);
            GetProvince(tbl.ProvinceId);
            return View(tbl);
        }

        //
        // POST: /District/Edit/5
        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult EditDistrict(tblDistrict tbl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    districtRepository.UpdDistrict(tbl);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Edit District";
                    tbllog.Description = tbl.DistrictName;
                    logRepository.InsLog(tbllog);

                }
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình lưu");
            }
            return RedirectToAction("District", new { name = 1 });
        }

        //
        // POST: /District/Delete/5
        [Authorize(Roles = "admin")]
        public ActionResult DeleteDistrict(int id)
        {
            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = "Delete District";
            tblDistrict tbl = districtRepository.GetDistrictById(id);
            tbllog.Description = tbl.DistrictName;
            logRepository.InsLog(tbllog);

            districtRepository.DelDistrict(id);
            return RedirectToAction("District", new { name = 1 });
        }

        ///
        ///Manage Section
        ///
        //
        // GET: /Section/
        [Authorize(Roles = "admin")]
        public ActionResult Section()
        {
            return View(sectionRepository.GetListSections());
        }

        //
        // GET: /Section/Create
        [Authorize(Roles = "admin")]
        public ActionResult CreateSection()
        {
            return View();
        }

        //
        // POST: /Section/Create
        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult CreateSection(tblSection collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    sectionRepository.InsSection(collection);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Create Section";
                    tbllog.Description = collection.SectionName_Vn;
                    logRepository.InsLog(tbllog);
                }
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình thêm mới");
            }
            return RedirectToAction("Section");
        }

        //
        // GET: /Section/Edit/5
        [Authorize(Roles = "admin")]
        public ActionResult EditSection(int id)
        {
            tblSection tbl = sectionRepository.GetSectionById(id);
            return View(tbl);
        }

        //
        // POST: /Section/Edit/5
        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult EditSection(tblSection collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    sectionRepository.UpdSection(collection);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Edit Section";
                    tbllog.Description = collection.SectionName_Vn;
                    logRepository.InsLog(tbllog);
                }
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình lưu");
            }
            return RedirectToAction("Section");
        }


        [Authorize(Roles = "admin")]
        public ActionResult DeleteSection(int id)
        {
            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = "Delete Section";
            tblSection tbl = sectionRepository.GetSectionById(id);
            tbllog.Description = tbl.SectionName_Vn;
            logRepository.InsLog(tbllog);

            sectionRepository.DelSection(id);
            return RedirectToAction("Section");
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        public ActionResult Customer()
        {
            ViewBag.Stt = 1;
            return View(customerRepository.GetListCustomers());
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        public ActionResult CreateCustomer()
        {
            GetListUserAccount();
            return View();
        }

        public void GetListUserAccount(object obj = null)
        {
            Roles.GetUsersInRole("Account");
            List<string> lst = new List<string>();
            lst.Add(hsTextNhanVien);
            foreach (string strUser in Roles.GetUsersInRole("Account"))
            {
                lst.Add(Membership.GetUser(strUser).UserName);
            }
            ViewBag.User = new SelectList(lst, obj);
        }


        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        [HttpPost]
        public ActionResult CreateCustomer(tblCustomer collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    MembershipCreateStatus createStatus;
                    Membership.CreateUser(collection.UserName, "123456", null, null, null, true, null, out createStatus);
                    Roles.AddUserToRole(collection.UserName, "Customer");
                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        if (collection.UserId == hsTextNhanVien)
                            collection.UserId = null;

                        customerRepository.InsCustomer(collection);

                        tblLog tbllog = new tblLog();
                        tbllog.UserName = Membership.GetUser().UserName;
                        tbllog.CreateDate = DateTime.Now;
                        tbllog.ActionName = "Create Customer";
                        tbllog.Description = collection.CompanyName;
                        logRepository.InsLog(tbllog);
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorCodeToString(createStatus));
                    }
                }
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình thêm mới");
            }
            return RedirectToAction("Customer");
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        public ActionResult EditCustomer(int id)
        {
            tblCustomer tbl = customerRepository.GetCustomerById(id);
            GetListUserAccount(tbl.UserId);
            return View(tbl);
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        [HttpPost]
        public ActionResult EditCustomer(tblCustomer collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    MembershipUser mbsUser = Membership.GetUser(collection.UserName);
                    if (mbsUser != null)
                    {
                        if (collection.UserId == hsTextNhanVien)
                            collection.UserId = null;
                        Membership.UpdateUser(mbsUser);
                    }
                    else
                    {
                        MembershipCreateStatus createStatus;
                        Membership.CreateUser(collection.UserName, "123456", null, null, null, true, null, out createStatus);
                        Roles.AddUserToRole(collection.UserName, "Customer");
                    }

                    customerRepository.UpdCustomer(collection);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Edit Customer";
                    tbllog.Description = collection.CompanyName;
                    logRepository.InsLog(tbllog);
                }
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình lưu");
            }
            return RedirectToAction("Customer");
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        public ActionResult DeleteCustomer(int id)
        {
            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = "Delete Customer";
            tblCustomer tbl = customerRepository.GetCustomerById(id);
            tbllog.Description = tbl.CompanyName;
            logRepository.InsLog(tbllog);

            customerRepository.DelCustomer(id);
            return RedirectToAction("Customer");
        }

        [Authorize(Roles = "admin")]
        public ActionResult Company()
        {
            return View(companyRepository.GetListCompanys());
        }

        //
        // GET: /Company/Create
        [Authorize(Roles = "admin")]
        public ActionResult CreateCompany()
        {
            return View();
        }

        //
        // POST: /Company/Create
        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult CreateCompany(tblCompany collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    companyRepository.InsCompany(collection);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Create Company";
                    tbllog.Description = collection.CompanyName_Vn;
                    logRepository.InsLog(tbllog);
                }
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá thêm mới");
            }
            return RedirectToAction("Company");
        }

        //
        // GET: /Company/Edit/5
        [Authorize(Roles = "admin")]
        public ActionResult EditCompany(int id)
        {
            tblCompany tbl = companyRepository.GetCompanyById(id);
            return View(tbl);
        }

        //
        // POST: /Company/Edit/5
        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult EditCompany(tblCompany tbl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    companyRepository.UpdCompany(tbl);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Edit Company";
                    tbllog.Description = tbl.CompanyName_Vn;
                    logRepository.InsLog(tbllog);
                }
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình lưu");
            }
            return RedirectToAction("Company");
        }

        //
        [Authorize(Roles = "admin")]
        public ActionResult DeleteCompany(int id)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Delete Company";
                    tblCompany tbl = companyRepository.GetCompanyById(id);
                    tbllog.Description = tbl.CompanyName_Vn;
                    logRepository.InsLog(tbllog);

                    companyRepository.DelCompany(id);
                }
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình xóa");
            }
            return RedirectToAction("Company");
        }

        ///
        ///Manage Station
        ///
        //
        // GET: /Station/
        [Authorize(Roles = "admin")]
        public ActionResult Station(string name, string StationName)
        {
            string s = string.Format("{0}", RouteData.Values["name"]);
            string strPage = string.IsNullOrEmpty(s) || !VoiceAd.Common.MyFunction.ValidateNumber(s) ? "1" : s;

            int intPageSize = 15;
            var lst = stationRepository.GetListSearchStations(StationName);
            int intSum = lst.Count();
            int intDu = intSum % intPageSize;
            int intPage = intSum / intPageSize;
            if (intDu > 0)
                intPage++;

            int intPos = (int.Parse(strPage) * intPageSize - intPageSize);
            ViewBag.stt = intPos + 1;
            string strAction = Url.Content("~/station-");

            ViewBag.paging = strPage;
            ViewBag.SumPage = intPage;
            ViewBag.lstPage = VoiceAd.Common.MyFunction.lstPaging(intPage, int.Parse(strPage), strAction);
            ViewBag.Action = strAction;
            ViewBag.LstProvinces = stationRepository.GetListStations().Skip(intPos).Take(intPageSize);

            return View(stationRepository.GetListSearchStations(StationName).Skip(intPos).Take(intPageSize));
        }

        //
        // GET: /Station/Create
        [Authorize(Roles = "admin")]
        public ActionResult CreateStation()
        {
            GetProvince();
            GetDistrict();
            return View();
        }

        public JsonResult CatType_SelectedState(string id)
        {
            int cid = int.Parse(id);
            JsonResult result = new JsonResult();
            result.Data = GetSubbuttonsSelectListItem(cid);
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        private List<SelectListItem> GetSubbuttonsSelectListItem(int cat_type_id)
        {
            var lst = (from p in districtRepository.GetByProvinceId(cat_type_id)
                       select new SelectListItem
                       {
                           Text = p.DistrictName,
                           Value = p.Id.ToString()
                       }).ToList();
            return lst;
        }

        public JsonResult Station_SelectedState(string id)
        {
            int cid = int.Parse(id);
            JsonResult result = new JsonResult();
            result.Data = GetStationByProvince(cid);
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        private List<SelectListItem> GetStationByProvince(int cat_type_id)
        {
            var lst = (from p in stationRepository.GetListStationByProvinceId(cat_type_id)
                       select new SelectListItem
                       {
                           Text = p.StationName,
                           Value = p.Id.ToString()
                       }).ToList();
            return lst;
        }

        //
        // POST: /Station/Create
        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult CreateStation(tblStation collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // Attempt to register the user
                    MembershipCreateStatus createStatus;
                    Membership.CreateUser(collection.UserName, "123456", collection.Email, null, null, true, null, out createStatus);
                    Roles.AddUserToRole(collection.UserName, "Station");
                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        stationRepository.InsStation(collection);

                        tblLog tbllog = new tblLog();
                        tbllog.UserName = Membership.GetUser().UserName;
                        tbllog.CreateDate = DateTime.Now;
                        tbllog.ActionName = "Create Station";
                        tbllog.Description = collection.StationName;
                        logRepository.InsLog(tbllog);
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorCodeToString(createStatus));
                    }
                }
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình thêm mới");
            }
            return RedirectToAction("Station", new { name = 1 });
        }

        //
        // GET: /Station/Edit/5
        [Authorize(Roles = "admin")]
        public ActionResult EditStation(int id)
        {
            //GetProvince();
            GetDistrict();
            return View(stationRepository.GetStationById(id));
        }

        //
        // POST: /Station/Edit/5
        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult EditStation(tblStation collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // Attempt to register the user                    
                    MembershipUser mbsUser = Membership.GetUser(collection.UserName);
                    if (mbsUser != null)
                    {
                        mbsUser.Email = collection.Email;
                        Membership.UpdateUser(mbsUser);
                    }
                    else
                    {
                        // Attempt to register the user
                        MembershipCreateStatus createStatus;
                        Membership.CreateUser(collection.UserName, "123456", collection.Email, null, null, true, null, out createStatus);
                        Roles.AddUserToRole(collection.UserName, "Station");
                    }
                    stationRepository.UpdStation(collection);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Edit Station";
                    tbllog.Description = collection.StationName;
                    logRepository.InsLog(tbllog);
                }
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình lưu");
            }
            return RedirectToAction("Station", new { name = 1 });
        }

        //
        // POST: /Station/Delete/5
        [Authorize(Roles = "admin")]
        public ActionResult DeleteStation(int id)
        {
            try
            {
                tblLog tbllog = new tblLog();
                tbllog.UserName = Membership.GetUser().UserName;
                tbllog.CreateDate = DateTime.Now;
                tbllog.ActionName = "Delete Station";
                tblStation tbl = stationRepository.GetStationById(id);
                tbllog.Description = tbl.StationName;
                logRepository.InsLog(tbllog);

                stationRepository.DelStation(id);
            }
            catch
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình xóa");
            }
            return RedirectToAction("Station");
        }

        /// <summary>
        ///Manage Services
        /// </summary>
        /// <param name="disposing"></param>
        //
        // GET: /Services/
        [Authorize(Roles = "admin")]
        public ActionResult Services()
        {
            ViewBag.stt = 1;
            return View(servicesRepository.GetListService());
        }

        //
        // GET: /Services/Details/5
        [Authorize(Roles = "admin")]
        public ActionResult DetailsServices(int id)
        {
            return View(servicesRepository.GetServiceById(id));
        }

        //
        // GET: /Services/Create
        [Authorize(Roles = "admin")]
        public ActionResult CreateServices()
        {
            return View();
        }

        //
        // POST: /Services/Create
        [Authorize(Roles = "admin")]
        [HttpPost, ValidateInput(false)]
        public ActionResult CreateServices(tblServices tbl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    servicesRepository.InsService(tbl);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Create Services";
                    tbllog.Description = tbl.Title_Vn;
                    logRepository.InsLog(tbllog);
                }

                return RedirectToAction("Services");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Services/Edit/5
        [Authorize(Roles = "admin")]
        public ActionResult EditServices(int id)
        {
            return View(servicesRepository.GetServiceById(id));
        }

        //
        // POST: /Services/Edit/5
        [Authorize(Roles = "admin")]
        [HttpPost, ValidateInput(false)]
        public ActionResult EditServices(tblServices tbl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    servicesRepository.UpdService(tbl);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Edit Services";
                    tbllog.Description = tbl.Title_Vn;
                    logRepository.InsLog(tbllog);
                }
                // TODO: Add update logic here

                return RedirectToAction("Services");
            }
            catch
            {
                return View();
            }
        }



        //
        [Authorize(Roles = "admin")]
        public ActionResult DeleteServices(int id)
        {
            try
            {
                tblLog tbllog = new tblLog();
                tbllog.UserName = Membership.GetUser().UserName;
                tbllog.CreateDate = DateTime.Now;
                tbllog.ActionName = "Delete Services";
                tblServices tbl = servicesRepository.GetServiceById(id);
                tbllog.Description = tbl.Title_Vn;
                logRepository.InsLog(tbllog);

                servicesRepository.DelService(id);

                return RedirectToAction("Services");
            }
            catch
            {
                return View();
            }
        }


        //
        // GET: /BroadCast/
        //
        // GET: /BroadCast/
        [Authorize(Roles = "admin")]
        public ActionResult BroadCast(string name, string StationName)
        {
            string s = string.Format("{0}", RouteData.Values["name"]);
            string strPage = string.IsNullOrEmpty(s) || !VoiceAd.Common.MyFunction.ValidateNumber(s) ? "1" : s;

            int intPageSize = 15;
            var lst = broadCastRepository.GetListSearchBroadCasts(StationName);
            int intSum = lst.Count();
            int intDu = intSum % intPageSize;
            int intPage = intSum / intPageSize;
            if (intDu > 0)
                intPage++;

            int intPos = (int.Parse(strPage) * intPageSize - intPageSize);
            ViewBag.stt = intPos + 1;
            string strAction = Url.Content("~/broadCast-");

            ViewBag.paging = strPage;
            ViewBag.SumPage = intPage;
            ViewBag.lstPage = VoiceAd.Common.MyFunction.lstPaging(intPage, int.Parse(strPage), strAction);
            ViewBag.Action = strAction;
            return View(broadCastRepository.GetListSearchBroadCasts(StationName).Skip(intPos).Take(intPageSize));
        }

        //
        // GET: /BroadCast/Create
        [Authorize(Roles = "admin")]
        public ActionResult CreateBroadCast()
        {
            GetSection();
            GetStation();
            GetProvince();
            return View();
        }

        //
        // POST: /BroadCast/Create
        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult CreateBroadCast(tblBroadCast collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    broadCastRepository.InsBroadCast(collection);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Create BroadCast";
                    tblStation tbl = stationRepository.GetStationById(Convert.ToInt32(collection.StationId));
                    tbllog.Description = tbl.StationName;
                    logRepository.InsLog(tbllog);
                }
                return RedirectToAction("BroadCast", new { name = 1 });
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /BroadCast/Edit/5
        [Authorize(Roles = "admin")]
        public ActionResult EditBroadCast(int id)
        {
            GetStation();
            GetSection();
            return View(broadCastRepository.GetBroadCastById(id));
        }

        //
        // POST: /BroadCast/Edit/5
        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult EditBroadCast(tblBroadCast collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    broadCastRepository.UpdBroadCast(collection);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Edit BroadCast";
                    tblStation tbl = stationRepository.GetStationById(Convert.ToInt32(collection.StationId));
                    tbllog.Description = tbl.StationName;
                    logRepository.InsLog(tbllog);
                }
                // TODO: Add update logic here

                return RedirectToAction("BroadCast", new { name = 1 });
            }
            catch
            {
                return View();
            }
        }


        //
        // POST: /BroadCast/Delete/5    
        [Authorize(Roles = "admin")]
        public ActionResult DeleteBroadCast(int id)
        {
            try
            {
                tblLog tbllog = new tblLog();
                tbllog.UserName = Membership.GetUser().UserName;
                tbllog.CreateDate = DateTime.Now;
                tbllog.ActionName = "Delete BroadCast";
                tblBroadCast collection = broadCastRepository.GetBroadCastById(id);
                tblStation tbl = stationRepository.GetStationById(Convert.ToInt32(collection.StationId));
                tbllog.Description = tbl.StationName;
                logRepository.InsLog(tbllog);

                broadCastRepository.DelBroadCast(id);

                return RedirectToAction("BroadCast");
            }
            catch
            {
                return View("BroadCast");
            }
        }

        [Authorize(Roles = "admin, account, Manager, Supervisor, Director")]
        public ActionResult Campaign()
        {
            ViewBag.stt = 1;
            if (Roles.IsUserInRole("account"))
                return View(campaignRepository.GetListCampaignsByUserId(Membership.GetUser().UserName).ToList());
            else

                return View(campaignRepository.GetListCampaigns().ToList());
        }

        [Authorize(Roles = "admin, account, Manager, Supervisor, Director")]
        public ActionResult ApproveCampaign(int id)
        {
            try
            {
                tblCampaign tbl = campaignRepository.GetCampaignById(id);
                if (tbl.Approve == true)
                {
                    tbl.Approve = false;
                }
                else
                {
                    tbl.Approve = true;
                }

                campaignRepository.UpdCampaign(tbl);

                tblLog tbllog = new tblLog();
                tbllog.UserName = Membership.GetUser().UserName;
                tbllog.CreateDate = DateTime.Now;
                tbllog.ActionName = "Approve Campaign";
                tbllog.Description = tbl.Title;
                logRepository.InsLog(tbllog);

                return RedirectToAction("Campaign");
            }
            catch
            {
                return View();
            }
        }

        [Authorize(Roles = "admin, account, Manager, Director")]
        public ActionResult DeleteCampaignWithDetail(int id)
        {
            try
            {
                tblLog tbllog = new tblLog();
                tbllog.UserName = Membership.GetUser().UserName;
                tbllog.CreateDate = DateTime.Now;
                tbllog.ActionName = "Delete Campaign";
                tblCampaign tbl = campaignRepository.GetCampaignById(id);
                tbllog.Description = tbl.Title;
                logRepository.InsLog(tbllog);

                campaignRepository.DeleteCampaignWithDetail(id);
                return RedirectToAction("Campaign");
            }
            catch
            {
                return View("Campaign");
            }
        }


        [Authorize(Roles = "admin, media, Manager")]
        public ActionResult SendMail(int CampaignId, int GroupId)
        {
            try
            {
                IEnumerable<tblSendMailGroup> lstEmailCampaign = sendMailGroupRepository.GetByCampaignIDGroupNum(CampaignId, GroupId);

                string lEmail = string.Empty;
                foreach (tblSendMailGroup objEc in lstEmailCampaign)
                {
                    string[] words = objEc.Email.Split(';');
                    foreach (string word in words)
                    {
                        try
                        {
                            tblStation tblst = stationRepository.GetStationById(Convert.ToInt32(objEc.StationId));
                            tblCampaign tblcp = campaignRepository.GetCampaignById(Convert.ToInt32(objEc.CampaignId));
                            SendMailCampaign(word, tblst.StationName, tblcp.Title, Convert.ToDateTime(tblcp.BeginDay).ToString("dd/MM/yyyy"));
                        }
                        catch (Exception ex)
                        {
                            tblSendMailStatus tblst = new tblSendMailStatus();
                            tblst.Email = word;
                            tblst.CampaingId = objEc.CampaignId;
                            tblst.StationId = objEc.StationId;
                            tblst.Massage = ex.Message;
                            sendMailStatusRepository.InsSendMailStatus(tblst);
                        }
                    }
                }
                ViewBag.lstEmail = lEmail;

                tblLog tbllog = new tblLog();
                tbllog.UserName = Membership.GetUser().UserName;
                tbllog.CreateDate = DateTime.Now;
                tbllog.ActionName = "SendMail Campaign";
                tblCampaign tbl = campaignRepository.GetCampaignById(CampaignId);
                tbllog.Description = tbl.Title;
                logRepository.InsLog(tbllog);

                return RedirectToAction("Campaign");
            }
            catch
            {
                return RedirectToAction("Campaign");
            }
        }


        protected void SendMailCampaign(string lEmail, string lStationName, string lCampaingName, string lStartDate)
        {
            try
            {
                tblEmailContent tbl = emailContentRepository.GetList().FirstOrDefault();
                var fromAddress = "campaign@tamanad.vn";
                var toAddress = lEmail;
                string fromPassword = "tamanad123456";
                var smtp = new System.Net.Mail.SmtpClient();
                {
                    smtp.Host = "smtp.live.com";
                    smtp.Port = Convert.ToInt32("587");
                    smtp.EnableSsl = Convert.ToBoolean("True");
                    smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
                    smtp.Timeout = Convert.ToInt32("20000");
                }

                string lBody = "Kính gửi đài phát thanh " + lStationName
                    + Environment.NewLine
                    + Environment.NewLine + "Cty TNHH TM Quảng Cáo Tâm An xin gửi đến quý anh/chị lịch book quảng cáo sản phẩm " + lCampaingName + ", bắt đầu chạy lịch vào ngày " + lStartDate + " anh/chị vui lòng cập nhật và cho phát sóng đúng ngày giúp Cty Tâm An."
                    + Environment.NewLine + "Khi nhận được mail book lịch quảng cáo này, anh/chị vui lòng reply xác nhận chạy lịch để Cty Tâm An làm ủy nhiệm chi chuyển tiền cho quý anh/chị theo đúng tiến độ."
                    + Environment.NewLine
                    + Environment.NewLine + "Cần hổ trợ thêm anh/chị vui lòng liên lạc lại với chúng tôi theo contact sau: Ms Phùng Thị Hải Lý  - Admin Manager hoặc Ms Dương Thị Kim Hương - Media Excecutive."
                    + Environment.NewLine + "Hotline: 0909 877 411."
                    + Environment.NewLine + "Tell: 08 6680 9826."
                    + Environment.NewLine
                    + Environment.NewLine + "Best regards,";

                //string lBody = "Kính gửi Các Anh/Chị nhà Đài! "
                //    + Environment.NewLine
                //    + Environment.NewLine + "Em tên: Dương Thị Kim Hương. Là nhân viên Media của Công Ty TNHH TM QC Tâm An. Địa chỉ trụ sở chính nằm tại: 387-389 Hai Bà Trưng, Phường 8, Quận 3, TPHCM."
                //    + Environment.NewLine
                //    + Environment.NewLine + "Hiện tại Công ty của em đang có nhu cầu quảng cáo trên hệ thống Loa Phát Thanh của đài mình."
                //    + Environment.NewLine
                //    + Environment.NewLine + "Em gửi anh/chị HỢP ĐỒNG NGUYÊN TẮC và HỢP ĐỒNG CỘNG TÁC VIÊN để anh/chị xem qua trình ký và gửi lại giúp em."
                //    + Environment.NewLine
                //    + Environment.NewLine + "Khi nhận được mail này anh/chị vui lòng reply lại cho em biết với nha. Chân thành cảm ơn sự hợp tác của anh/chị rất nhiều."
                //    + Environment.NewLine
                //    + Environment.NewLine + "Lưu ý: Với Hợp Đồng Cộng Tác Viên các anh/ chị vui lòng in hai bản và gửi đính kèm giúp em một bản photo CMND (không cần công chứng)."
                //    + Environment.NewLine
                //    + Environment.NewLine + "Tải file Hợp Đồng Nguyên Tắc. http://tamanad.vn/uploads/docs/HD_nguyen_tac_cam_ket_ds.docx"
                //    + Environment.NewLine
                //    + Environment.NewLine + "Tải file Hợp Đồng Cộng Tác Viên. http://tamanad.vn/uploads/docs/HDCTV_NV_DAI.doc"
                //    + Environment.NewLine
                //    + Environment.NewLine + "Best regards,"
                //    + Environment.NewLine + "----------------------------------------------------------------------------------------"
                //    + Environment.NewLine + "Duong Thi Kim Huong | Media Executive"
                //    + Environment.NewLine + "Tam An Advertising Trading Company Limited"
                //    + Environment.NewLine + "Fl 4 - Room 403, 387- 389 Hai Bà Trưng Str.,| 3 Dictrict | HCMC"
                //    + Environment.NewLine + "Tel: 08 6680 9826 - Fax: 08 3820 1233 - Phone: 0937 375 771"
                //    + Environment.NewLine + "Email: huong.duong@tamanad.vn";

                smtp.Send(fromAddress, toAddress, tbl.Title, lBody);
                //smtp.Send(fromAddress, toAddress, "Hợp đồng nguyên tắc & HĐ cộng tác viên - Cty TNHH TM Quảng Cáo Tâm An", lBody);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        public ActionResult ListStation(int id, string name, string StationName)
        {
            string s = string.Format("{0}", RouteData.Values["name"]);
            string strPage = string.IsNullOrEmpty(s) || !VoiceAd.Common.MyFunction.ValidateNumber(s) ? "1" : s;

            int intPageSize = 15;
            var lst = bookingRepostitory.GetListBookingsByCampIdAndStationName(id, StationName);
            int intSum = lst.Count();
            int intDu = intSum % intPageSize;
            int intPage = intSum / intPageSize;
            if (intDu > 0)
                intPage++;

            int intPos = (int.Parse(strPage) * intPageSize - intPageSize);
            ViewBag.stt = intPos + 1;
            string strAction = Url.Content("~/list-station-" + id + "-");

            ViewBag.paging = strPage;
            ViewBag.SumPage = intPage;
            ViewBag.lstPage = VoiceAd.Common.MyFunction.lstPaging(intPage, int.Parse(strPage), strAction);
            ViewBag.Action = strAction;
            ViewBag.CampId = id;
            ViewBag.CamPaignName = campaignRepository.GetCampaignById(id).Title;

            IEnumerable<tblAudioCamp> tblaudioCamp = audioCampRepository.GetListAudioCampsbyCampId(id);
            foreach (tblAudioCamp tbl in tblaudioCamp)
            {
                ViewData["audioCampId"] = tbl.Id;
            }

            return View(bookingRepostitory.GetListBookingsByCampIdAndStationName(id, StationName).Skip(intPos).Take(intPageSize));
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        public ActionResult ListBookingStation(int id)
        {
            tblBooking tbl = bookingRepostitory.GetBookingById(id);
            ViewData["IdCamp"] = tbl.CampaignId;
            ViewData["IdStation"] = tbl.StationId;
            ViewBag.lstMonitor = monitorRepository.GetListMonitorsByBookingAd(id);
            ViewBag.lstBooking = blockingRepository.GetListBlockByBooking(id);

            ViewBag.DetailTitle = "Chiến dịch " + tbl.tblCampaign.Title + " - " + "Nhà đài " + tbl.tblStation.StationName;

            return View();
        }

        //
        [Authorize(Roles = "admin")]
        public ActionResult DeleteBlockById(int id)
        {
            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = "Delete Block";
            tblBlock tbl = blockingRepository.GetBlockById(id);
            tbllog.Description = tbl.BookingId.ToString() + tbl.MonthBook.ToString();
            logRepository.InsLog(tbllog);

            blockingRepository.DelBlock(id);
            return RedirectToAction("ListBookingStation", new { id = tbl.BookingId });
        }

        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult ListBookingStation(string txtDay, string txtUrl, string CampId, string IdStation)
        {
            tblMonitor tbl = new tblMonitor();
            tblBooking objBook = bookingRepostitory.GetBookingByCampId(int.Parse(CampId), int.Parse(IdStation));
            tblCampaign objCamp = campaignRepository.GetCampaignById(int.Parse(CampId));
            tblStation objStaion = stationRepository.GetStationById(int.Parse(IdStation));

            tbl.BookingId = objBook.Id;

            tbl.UploadDay = DateTime.Parse(string.Format("{0:yyyy/MM/dd}", txtDay));

            if (!string.IsNullOrEmpty(txtUrl) && txtUrl.Contains(";"))
                txtUrl = txtUrl.Replace(";", "");

            int intCount = monitorRepository.GetSumMonitorByUploadDay(objBook.Id, tbl.UploadDay.Value);

            tbl.UrlFile = UpdateFile(txtUrl, objCamp.Title, tbl.UploadDay.Value.ToString("yyyyMM"), tbl.UploadDay.Value.ToString("yyyyMMdd"), intCount, objStaion.UserName);
            monitorRepository.InsMonitor(tbl);

            return RedirectToAction("ListBookingStation", new { id = objBook.Id });
        }




        [Authorize(Roles = "admin")]
        public string UpdateFile(string strName, string strCamp, string strDate, string strDay, int intCount, string stationName)
        {
            string strPath = Server.MapPath("~/uploads");
            string strFile = Path.Combine(Server.MapPath("~/uploads"), strName);
            string strExt = Path.GetExtension(strFile);
            string strFolder = Path.Combine(strPath, "Station");
            string strIdCamp = string.Empty;
            string strIdDate = string.Empty;

            if (!Directory.Exists(strFolder))
                Directory.CreateDirectory(strFolder);

            strIdCamp = Path.Combine(strFolder, strCamp);

            if (!Directory.Exists(strIdCamp))
                Directory.CreateDirectory(strIdCamp);

            strIdDate = Path.Combine(strIdCamp, strDate);

            if (!Directory.Exists(strIdDate))
                Directory.CreateDirectory(strIdDate);

            string strResult = stationName + "-" + strDay + "-0" + (intCount + 1).ToString() + strExt;
            strFolder = Path.Combine(strIdDate, strResult);
            System.IO.File.Copy(strFile, strFolder, true);

            return "Station/" + strCamp + "/" + strDate + "/" + strResult;
        }

        [Authorize(Roles = "admin")]
        public ActionResult DeleteMonitor(int id, int BookingId)
        {
            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = "Delete Minitor File";
            tblMonitor tbl = monitorRepository.GetMonitorById(id);
            tbllog.Description = "Chiến dịch: " + tbl.tblBooking.tblCampaign.Title + " Nhà đài: " + tbl.tblBooking.tblStation.StationName;
            logRepository.InsLog(tbllog);

            monitorRepository.DelMonitor(id);
            return RedirectToAction("ListBookingStation", new { id = BookingId });
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        public ActionResult ChangeDay(int id)
        {
            return View(blockingRepository.GetBlockById(id));
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        [HttpPost]
        public ActionResult ChangeDay(tblBlock tbl)
        {
            tblBlock obj = blockingRepository.GetBlockById(tbl.Id);
            obj.DayBook = tbl.DayBook;
            obj.MonthPrice = tbl.MonthPrice;
            blockingRepository.UpdBlock(obj);
            return RedirectToAction("ListBookingStation", new { id = obj.BookingId });
        }

        public ActionResult SendMailByGroup(int CampaignId)
        {
            ViewBag.CampaignName = campaignRepository.GetCampaignById(CampaignId).Title;
            return View(sendMailGroupRepository.GetListGroup(CampaignId));
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

        protected override void Dispose(bool disposing)
        {
            provinceRepository.Dispose();
            districtRepository.Dispose();
            sectionRepository.Dispose();
            customerRepository.Dispose();
            companyRepository.Dispose();
            stationRepository.Dispose();
            servicesRepository.Dispose();
            broadCastRepository.Dispose();
            campaignRepository.Dispose();
            bookingRepostitory.Dispose();
            blockingRepository.Dispose();
            monitorRepository.Dispose();
            sendMailStatusRepository.Dispose();
            emailContentRepository.Dispose();
            logRepository.Dispose();
            contentRepository.Dispose();
        }

        public ActionResult ManagesUsers()
        {
            string[] lstRoles = { "admin", "Account", "Media", "Manager", "Supervisor", "Director" };
            MembershipUserCollection lstUser = new MembershipUserCollection();

            foreach (string strRoles in lstRoles)
            {
                foreach (string strUser in Roles.GetUsersInRole(strRoles))
                {
                    lstUser.Add(Membership.GetUser(strUser));
                }
            }

            ViewBag.stt = 1;

            return View(lstUser);
        }

        public ActionResult DelUser(string id)
        {
            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = "Delete User";

            MembershipUser user;
            user = Membership.GetUser(id);

            tbllog.Description = user.UserName;
            logRepository.InsLog(tbllog);

            Membership.DeleteUser(id);
            return RedirectToAction("ManagesUsers");
        }

        public ActionResult ResetPass(string id)
        {
            MembershipUser user;

            user = Membership.GetUser(id);
            if (user.IsLockedOut == true)
                user.UnlockUser();

            user.ChangePassword(user.ResetPassword(), "123456");

            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = "Reset Pass";
            tbllog.Description = user.UserName;
            logRepository.InsLog(tbllog);

            return RedirectToAction("ManagesUsers");
        }

        public void GetRoles(object obj = null)
        {
            string[] lstRoles = { "admin", "Account", "Media", "Manager", "Supervisor", "Director" };
            ViewBag.Roles = new SelectList(lstRoles, obj);
        }

        public ActionResult AddUser()
        {
            GetRoles();
            return View();
        }

        [HttpPost]
        public ActionResult AddUser(RegisterModel model, string RoleId)
        {
            if (ModelState.IsValid)
            {

                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    Roles.AddUserToRole(model.UserName, RoleId);

                    tblLog tbllog = new tblLog();
                    tbllog.UserName = Membership.GetUser().UserName;
                    tbllog.CreateDate = DateTime.Now;
                    tbllog.ActionName = "Add User";
                    tbllog.Description = model.UserName;
                    logRepository.InsLog(tbllog);

                    return RedirectToAction("ManagesUsers");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            GetRoles(RoleId);
            return View(model);
        }

        public ActionResult EditUser(string id)
        {
            MembershipUser u = Membership.GetUser(id);
            ViewData["UserName"] = u.UserName;
            ViewData["Email"] = u.Email;
            string[] lstRole = Roles.GetRolesForUser(id);
            GetRoles(lstRole.First());
            return View();
        }

        [HttpPost]
        public ActionResult EditUser(string id, string RoleId)
        {
            MembershipUser u = Membership.GetUser(id);
            Roles.RemoveUserFromRoles(id, Roles.GetRolesForUser(id));
            Roles.AddUserToRole(id, RoleId);

            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = "Edit User";
            tbllog.Description = u.UserName;
            logRepository.InsLog(tbllog);

            return RedirectToAction("ManagesUsers");
        }



        //Content
        //
        // GET: /Content/
        [Authorize(Roles = "admin")]
        public ActionResult Content()
        {
            return View(contentRepository.GetListContent());
        }

        //
        // GET: /Content/Create
        [Authorize(Roles = "admin")]
        public ActionResult CreateContent()
        {
            return View();
        }

        //
        // POST: /Content/Create
        [Authorize(Roles = "admin")]
        [HttpPost, ValidateInput(false)]
        public ActionResult CreateContent(tblContent tblcontent)
        {
            try
            {
                contentRepository.InsContent(tblcontent);

                tblLog tbllog = new tblLog();
                tbllog.UserName = Membership.GetUser().UserName;
                tbllog.CreateDate = DateTime.Now;
                tbllog.ActionName = "Add Content";
                tbllog.Description = tblcontent.Title_VI;
                logRepository.InsLog(tbllog);

                return RedirectToAction("Content");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Content/Edit/5
        [Authorize(Roles = "admin")]
        public ActionResult EditContent(int id)
        {
            return View(contentRepository.GetContentById(id));
        }

        //
        // POST: /Content/Edit/5
        [Authorize(Roles = "admin")]
        [HttpPost, ValidateInput(false)]
        public ActionResult EditContent(tblContent tblcontent)
        {
            try
            {
                // TODO: Add update logic here
                contentRepository.UpdContent(tblcontent);

                tblLog tbllog = new tblLog();
                tbllog.UserName = Membership.GetUser().UserName;
                tbllog.CreateDate = DateTime.Now;
                tbllog.ActionName = "UPdate Content";
                tbllog.Description = tblcontent.Title_VI;
                logRepository.InsLog(tbllog);

                return RedirectToAction("Content");
            }
            catch
            {
                return View();
            }
        }


        //
        // POST: /Content/Delete/5


        public ActionResult DeleteContent(int id)
        {
            try
            {
                tblLog tbllog = new tblLog();
                tbllog.UserName = Membership.GetUser().UserName;
                tbllog.CreateDate = DateTime.Now;
                tbllog.ActionName = "UPdate Content";
                tblContent content = contentRepository.GetContentById(id);
                tbllog.Description = content.Title_VI;
                logRepository.InsLog(tbllog);

                contentRepository.DelContent(id);

                return RedirectToAction("Content");
            }
            catch
            {
                return View();
            }
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        public ActionResult ApproveBlock(int id)
        {
            ViewBag.IdCamp = id;
            return View(blockingRepository.GetListApproveByCampId(id));
        }

        public ActionResult ApproveByBlock(int MonthId, int YearId, int Id, int bApprove)
        {
            blockingRepository.ApproveBlock(Id, YearId, MonthId, bApprove);
            return RedirectToAction("ApproveBlock", new { Id = Id });
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        public ActionResult AddStationCampaign(int campId, string name, string StationName)
        {
            string s = string.Format("{0}", RouteData.Values["name"]);
            string strPage = string.IsNullOrEmpty(s) || !VoiceAd.Common.MyFunction.ValidateNumber(s) ? "1" : s;

            int intPageSize = 15;
            var lst = stationRepository.GetListSearchStations(StationName);
            int intSum = lst.Count();
            int intDu = intSum % intPageSize;
            int intPage = intSum / intPageSize;
            if (intDu > 0)
                intPage++;

            int intPos = (int.Parse(strPage) * intPageSize - intPageSize);
            ViewBag.stt = intPos + 1;
            string strAction = Url.Content("~/station-");

            ViewBag.paging = strPage;
            ViewBag.SumPage = intPage;
            ViewBag.lstPage = VoiceAd.Common.MyFunction.lstPaging(intPage, int.Parse(strPage), strAction);
            ViewBag.Action = strAction;
            ViewBag.LstProvinces = stationRepository.GetListStations().Skip(intPos).Take(intPageSize);
            ViewBag.CampId = campId;
            return View(stationRepository.GetListSearchStations(StationName).Skip(intPos).Take(intPageSize));
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        public ActionResult AddStationByCampId(int id, int StationId)
        {
            campaignRepository.InsStationByCampId(id, StationId);
            return RedirectToAction("ListStation", new { id = id, name = "1" });
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        public ActionResult AddMonthCampaign(int id)
        {
            ViewBag.CampId = id;
            return View();
        }

        [Authorize(Roles = "admin, account, manager, supervisor, director")]
        [HttpPost]
        public ActionResult AddMonthCampaign(int id, string txtNam, string txtThang, string arrDay)
        {
            blockingRepository.tblBlockInsertMonth(id, int.Parse(txtNam), int.Parse(txtThang), arrDay);
            return RedirectToAction("ListStation", new { id = id, name = "1" });
        }
    }
}
